package com.ihcy.base.controller;

import com.ihcy.base.core.Result;
import com.ihcy.base.enums.PositioneEnum;
import com.ihcy.base.model.entity.User;
import com.ihcy.base.model.vo.request.RegisterUserRequest;
import com.ihcy.base.model.vo.request.UserQueryRequest;
import com.ihcy.base.model.vo.response.UserResponse;
import com.ihcy.base.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    private final IUserService userService;

    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("registerUser")
    public Result<UserResponse> registerUser(@RequestBody RegisterUserRequest request) {
        logger.info(request.getTestTime().toString());
        return Result.ok(UserResponse.build(userService.registerUser(User.build(request))));
    }

    @PostMapping("addBatchUser")
    public Result<Void> addBatchUser(@RequestBody List<RegisterUserRequest> list) {
        userService.addBatchUser(list);
        return Result.ok(null);
    }

    @DeleteMapping("deleteUser")
    public Result<Boolean> deleteUser(@RequestParam Long id) {
        return Result.ok(userService.deleteUser(id));
    }

    @GetMapping("findAll")
    public Result<List<UserResponse>> findAll() {
        return Result.ok(UserResponse.buildList(userService.findAll()));
    }

    /**
     * http://localhost:8080/user/getPage?page=0&size=3&sort=createdTime,desc
     */
    @PostMapping("getPage")
    public Result<Page<UserResponse>> getPage(@RequestBody UserQueryRequest request, Pageable pageable) {
        Page<User> userPage = userService.getPage(request, pageable);
        return Result.ok(userPage.map(UserResponse::build));
    }

    @GetMapping("getUserByPosition")
    public Result<List<UserResponse>> getUserByPosition(@RequestParam PositioneEnum position) {
        List<User> list = userService.getUserByPosition(position);
        return Result.ok(list.stream().map(UserResponse::build).collect(Collectors.toList()));
    }

    @GetMapping("getUserByPosition/{position}")
    public Result<List<UserResponse>> getUserByPositionPath(@PathVariable PositioneEnum position) {
        List<User> list = userService.getUserByPosition(position);
        return Result.ok(list.stream().map(UserResponse::build).collect(Collectors.toList()));
    }

    @GetMapping("testException")
    public Result<Void> testException() {
        userService.testException();
        return Result.ok(null);
    }
}
